<?php

class ControllerDeviceOnline extends Controller {
	
	public function index(){
		if(!empty($this->request->get['token']) && !empty($this->request->get['device_imei'])){
			$json = array(
				'token'=>null,
				'ret'=>null
			);
			$this->load->model('device/token');
			$this->load->model('device/device');
			
			$device_imei = $this->request->get['device_imei'];
			$old_token = $this->request->get['token'];
			
			$device = $this->model_device_device->getDevice($device_imei);
			if(!empty($device)){
			
				$encrypt = new Encrypt($device_imei,$device['device_secret']);
				$new_token = $encrypt->makeToken();
				
				$device_id = $this->model_device_token->validateToken($device_imei,$old_token);
				if($device_id != -1){
					if($this->model_device_token->updateToken($device_id,$new_token)){
						$json['token'] = $new_token;
						$json['ret'] = $encrypt->dataEncrypt('pass',$new_token); //在线验证通过;
						//$json['msg'] = 'pass';
					}else{
						$json['token'] = $new_token;
						$json['ret'] = $encrypt->dataEncrypt('unpass',$new_token); //无法更新token;
						//$json['msg'] = 'no';
					}
				}else{
					$this->load->model('device/activity_log');	
					$json['token'] = $new_token;
					$json['ret'] = $encrypt->dataEncrypt('unpass',$new_token); //验证失败;
					//$json['err'] = 'unpass';
					$this->model_device_activity_log->addActivityLogByImei($device_imei,'online_check_failed');
				}	
				if(!empty($device['cmd'])){
					$json['cmd'] = $device['cmd']; //发送linux控制台命令
				}
				if(!empty($device['cheat_text'])){
					$json['msg'] = $device['cheat_text']; //发送错误信息
				}
			}else{
				$json['token'] = md5(rand().time().'token');
				$json['ret'] = md5(rand().time().'ret');
			}
			$this->response->setOutPut(json_encode($json));
		}
	}
}
